<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function jsonp(url, data = {}, callback = 'callback') {
      // 处理json对象，拼接url
      data.callback = callback;
      let params = [];
      for (let key in data) {
        params.push(key + '=' + data[key]);
      }
      let script = document.createElement('script');
      script.src = url + '?' + params.join('&');
      console.log(script);
      document.body.appendChild(script);

      return new Promise((resolve, reject) => {
        console.log('wwww');
        // 将回调定义在window对象里面
        window[callback] = data => {
          try {
            resolve(data);
          } catch (err) {
            reject(err);
          } finally {
            script.parentNode.removeChild(script);
          }
        }
      })
    }

    // 请求数据
    jsonp('http://photo.sina.cn/aj/index', {
      page: 1,
      cate: 'recommend',
    }, 'jsoncallback').then(data => {
      console.log(data)
    })

    // 之后根据执行创建的script标签发送请求，
    // 服务器会自动的将所请求的数据放在回调函数的参数中将整个回调函数返回
    // 之后浏览器就会调用这个回调函数
  </script>
</body>

</html>